package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 存储喜欢的数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.检验参数
        if(dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录人的信息
        ApUser user = AppThreadUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3判断用户是否已经点赞，查询redis
        //3.1获取关注缓存hash类型的key
        String like_hash_key="USER_LIKES_"+dto.getArticleId();
        //3.2判断是否已经点赞,查询缓存中的小key是否包含点赞人的id
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(like_hash_key, user.getId() + "");

        //用户未点赞(并且有点赞请求)
        if(!aBoolean && dto.getOperation()==0){//要执行的点赞行为操作
        //    保存数据到redis中
            redisTemplate.opsForHash().put(like_hash_key,user.getId()+"","1");
        //    保存到mongodb中
            ApLikesBehavior apLikesBehavior=new ApLikesBehavior();
            apLikesBehavior.setUserId(user.getId().longValue());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setArticleId(dto.getArticleId());
            mongoTemplate.insert(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //用户已点赞
        if(aBoolean && dto.getOperation()==0){//已经点赞了,不能再点赞了
            return ResponseResult.errorResult(AppHttpCodeEnum.LIKES_USER_SUCCESS);
        }
        if(aBoolean && dto.getOperation()==1){//表示执行的是取消点赞的操作
        //    删除缓存数据
            redisTemplate.opsForHash().delete(like_hash_key,user.getId()+"");
        //    删除mongodb中的数据
            Query query=Query.query(Criteria.where("userId").is(user.getId()).and("articleId").is(dto.getArticleId()));
            mongoTemplate.remove(query,ApLikesBehavior.class);
            return ResponseResult.okResult(AppHttpCodeEnum.LIKES_CANCEL_SUCCESS);
        }
        return null;
    }
}
